package com.xfcycle.zebrabikegp.util;

import android.os.SystemClock;
import android.util.Log;

import com.xfcycle.zebrabikegp.listener.OnTimeOutListener;

import java.util.HashMap;
import java.util.Map;

/**
 * 定时线程工具类
 * Created by Wilson on 2017/7/4.
 */

public class TimingThreadUtil {
    private final static String TAG = "TimingThreadUtil";
    private static TimingThreadUtil instance;
    private static Map<String, Thread> threads;
    private static Map<String, Boolean> runStates;
    private static Map<String, OnTimeOutListener> onTimeOutListeners;

    private TimingThreadUtil() {
        threads = new HashMap<>();
        runStates = new HashMap<>();
        onTimeOutListeners = new HashMap<>();
    }

    public static TimingThreadUtil getInstance(String threadName, OnTimeOutListener onTimeOutListener) {
        if (null == instance) {
            instance = new TimingThreadUtil();
        }
        onTimeOutListeners.put(threadName, onTimeOutListener);
        return instance;
    }

    public void openThread(String threadName, int sleepTime) {

        final Boolean isRunning = runStates.get(threadName);
        runStates.put(threadName, true);

        //若没有该线程，则添加
        if (null == threads.get(threadName)) {
            startThread(threadName, sleepTime);
        }

        Thread currentThread = threads.get(threadName);

        Log.i(TAG, "openThread: ---------------   线程状态 " + currentThread.getName() + " ---- " +  currentThread.isAlive());

        //若线程被后台关闭，重启线程
        if(!currentThread.isAlive()){
            try {
                startThread(threadName, sleepTime);
            }catch (Exception e){
                e.printStackTrace();
                Log.i(TAG, "openThread: 开启线程失败");
                return;
            }
        }
        Log.i(TAG, "openThread: ------------------------- 开启 " + threadName + " 线程");
    }

    /**
     * 关闭一个线程
     */
    public static void closeThread(String threadName) {
        runStates.put(threadName, false);
        Log.i(TAG, "openThread: ------------------------- 关闭 " + threadName + " 线程");
    }

    /**
     * 关闭当前所有定时线程
     */
    public static void closeAllTiming() {
        for (Map.Entry<String, Boolean> runState : runStates.entrySet()) {
            runStates.put(runState.getKey(), false);
        }
    }

    /**
     * 开启一个线程
     */
    private static void startThread(final String threadName, final int sleepTime){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (runStates.get(threadName)) {
                    onTimeOutListeners.get(threadName).timeOut();
                    SystemClock.sleep(sleepTime);
                }
            }
        });

        thread.start();
        threads.put(threadName, thread);
    }
}
